package com.dge.common.utils

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Environment
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.FragmentActivity
import com.dge.common.bean.PgyerUpdateBean
import com.dge.common.common.AppConfig
import com.dge.common.common.Constants
import com.dge.common.common.UserInfoMgr
import com.dge.common.dialog.UpdateDialog
import com.dge.common.extentions.roundUp
import com.dge.common.other.IOSStyleDialogAnimator
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import timber.log.Timber
import java.io.IOException

/**
 * @auther Jasper Jiao
 * @time 2022/6/21 9:38
 * @des 升级工具类
 */
object UpdateUtils {
    /**
     * 更新取消一次，三天内不主动提示
     */
    fun canShowUpdateDialog(newVersionCode: Int): Boolean {
        // 如果isLastUpdateCanceled是true，则说明lastUpdateTimeMills和lastCanceledUpdateVersionCode一定记录了，
        // 则基于这两个变量的对比是有效的
        Timber.i(
            "isLastUpdateCanceled = ${UserInfoMgr.isLastUpdateCanceled}" +
                    ", lastCanceledUpdateVersionCode = ${UserInfoMgr.lastCanceledUpdateVersionCode}" +
                    ", AppConfig.getVersionCode() = ${AppConfig.getVersionCode()}" +
                    ",timeTrue? = ${UserInfoMgr.lastUpdateTimeMills + 1 * 24 * 60 * 60 * 1000 < System.currentTimeMillis()}" +
                    ",newVersionCode = $newVersionCode"
        )
        return !UserInfoMgr.isLastUpdateCanceled
                || (UserInfoMgr.isLastUpdateCanceled
                && UserInfoMgr.lastCanceledUpdateVersionCode > AppConfig.getVersionCode()
                && (UserInfoMgr.lastUpdateTimeMills + 1 * 24 * 60 * 60 * 1000 < System.currentTimeMillis()
                || newVersionCode > UserInfoMgr.lastCanceledUpdateVersionCode))
    }

    /**
     * 从蒲公英获取新版本并下载
     * @param isFromUser 是不是用户主动操作
     */
    private fun checkPgyerUpdate(activity: FragmentActivity, isFromUser: Boolean = false) {
        val abis = Utils.getABIs()
        //自动检查更新时过滤64位CPU架构和android12以下版本
        // if (!isFromUser && (abis.contains("arm64") || abis.contains("aarch64")) && Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
        //     Timber.i("isFromUser = $isFromUser, abis = $abis，version = ${Build.VERSION.SDK_INT}")
        //     return
        // }
        val mediaType = "application/x-www-form-urlencoded; charset=utf-8".toMediaTypeOrNull()
        val requestBody =
            "_api_key=" + Constants.PGY_API_KEY + "&buildShortcutUrl=" + Constants.PGY_SHORTCUT
        val request = Request.Builder()
            .url("https://www.pgyer.com/apiv2/app/getByShortcut")
            .post(RequestBody.create(mediaType, requestBody))
            .build()
        val okHttpClient = OkHttpClient()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Timber.i("onFailure:  ${e.message}")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                if (activity.isFinishing || activity.isDestroyed) return
                Timber.i(response.protocol.toString() + " " + response.code + " " + response.message)
                val headers = response.headers
                for (i in 0 until headers.size) {
                    Timber.i(headers.name(i) + ":" + headers.value(i))
                }
                val body = response.body!!.string()
                Timber.i("onResponse: $body")
                val updateBean = GsonUtils.gson.fromJson(body, PgyerUpdateBean::class.java)
                if (updateBean == null || updateBean.data == null) {
                    Timber.i("onResponse: updateBean = $updateBean, updateBean.data = ${updateBean?.data}")
                    return
                }
                val currentVersionCode: Int = AppConfig.getVersionCode()
                val remoteVersionCode = updateBean.data.buildVersionNo.toInt()
                val versionNameString = updateBean.data.buildName + updateBean.data.buildVersion
                val description = updateBean.data.buildUpdateDescription
                var isForce = false
                var des = description
                //最后5位是数字，其中倒数第一位是为了适配旧版，前4位是最后一个不强制更新的版本号，低于这个要强制更新
                if (description.length > 5) {
                    if (description.substring(description.length - 5).isDigitsOnly()) {
                        val lastCanStayVersionCode =
                            description.substring(description.length - 5, description.length - 1)
                        Timber.i("lastCanStayVersionCode = $lastCanStayVersionCode")
                        if (lastCanStayVersionCode.isDigitsOnly()) {
                            val lastVC = lastCanStayVersionCode.toInt() //最后一个可以不强制升级的版本
                            if (currentVersionCode < lastVC) isForce = true
                            des = description.substring(0, description.length - 5)
                        } else {
                            Timber.i("isNotDigitsOnly1")
                        }
                    } else { //适配倒数第一位不适配旧版的情况，也就是说最后4位是最后一个不强制更新的版本号
                        val lastCanStayVersionCode2 = description.substring(description.length - 4)
                        Timber.i("lastCanStayVersionCode2 = $lastCanStayVersionCode2, currentVersionCode = $currentVersionCode")
                        if (lastCanStayVersionCode2.isDigitsOnly()) {
                            val lastVC = lastCanStayVersionCode2.toInt() //最后一个可以不强制升级的版本
                            if (currentVersionCode < lastVC) isForce = true
                            des = description.substring(0, description.length - 4)
                        } else {
                            Timber.i("isNotDigitsOnly2")
                        }
                    }
                }
                Timber.i("isForce = $isForce")
                if (!isForce && !canShowUpdateDialog(remoteVersionCode) && !isFromUser) {
                    Timber.i("onResponse canShowUpdateDialog return")
                    response.close()
                    return
                }
                val fileSize = "${((updateBean.data.buildFileSize.toLong() * 1.0) / 1024 / 1024).roundUp(2)}M"
                if (remoteVersionCode > currentVersionCode) {
                    //自动检查更新，是强制时才显示，用户手动触发时，都会显示
                    if ((!isFromUser && isForce) || isFromUser) {
                        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                            val url =
                                "https://www.pgyer.com/apiv2/app/install?_api_key=" + Constants.PGY_API_KEY + "&appKey=" + Constants.PGY_APP_KEY
                            Thread {
                                var code = 500
                                var resp: Response? = null
                                try {
                                    resp =
                                        OkHttpUtils.get(url).execute(false)
                                    code = resp.code
                                } catch (e: Exception) {
                                }
                                Timber.i("showUpdateDialog url= $url")
                                Timber.i("showUpdateDialog code= " + code + "; message = " + resp?.message)
                                if (code == 302) {
                                    val downloadUrl = resp!!.header("Location")
                                    Timber.i("showUpdateDialog location= $downloadUrl")
                                    if (downloadUrl != null) {
                                        if (activity.isFinishing || activity.isDestroyed) return@Thread
                                        activity.runOnUiThread {
                                            XPopup.Builder(activity)
                                                .isDarkTheme(AppConfig.isDarkTheme())
                                                .customAnimator(IOSStyleDialogAnimator())
                                                .asCustom(
                                                    UpdateDialog(
                                                        activity,
                                                        versionNameString,
                                                        remoteVersionCode,
                                                        fileSize,
                                                        des,
                                                        downloadUrl,
                                                        isForce
                                                    )
                                                ).show()
                                        }
                                    } else {
                                        Timber.i("下载地址未找到")
                                        if (activity.isFinishing || activity.isDestroyed) return@Thread
                                        ToastUtils.show("下载地址未找到")
                                        resp.close()
                                        return@Thread
                                    }
                                } else {
                                    Timber.i("即将打开浏览器进行下载")
                                    if (activity.isFinishing || activity.isDestroyed) return@Thread
                                    ToastUtils.show("即将打开浏览器进行下载")
                                    Thread.sleep(1500)
                                    try {
                                        if (activity.isFinishing || activity.isDestroyed) return@Thread
                                        val myIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                                        activity.startActivity(myIntent)
                                    } catch (e: ActivityNotFoundException) {
                                        ToastUtils.show("未安装浏览器")
                                        e.printStackTrace()
                                    }
                                    resp?.close()
                                }
                            }.start()
                        } else {
                            Timber.i("Environment.getExternalStorageState() = ${Environment.getExternalStorageState()}")
                            if (activity.isFinishing || activity.isDestroyed) return
                            ToastUtils.show("内部存储不可用")
                        }
                    } else {
                        Timber.i("isFromUser = $isFromUser, isForce = $isForce")
                    }
                } else {
                    Timber.i("remoteVersionCode = ${remoteVersionCode}, currentVersionCode = $currentVersionCode")
                    if (activity.isFinishing || activity.isDestroyed) return
                    if (isFromUser) ToastUtils.show("已是最新版本")
                }
                response.close()
            }
        })
    }
    // /**
    //  * 通过bugly检查更新并下载
    //  * @param isFromUser 是不是用户主动操作
    //  */
    // private fun checkBuglyUpdate(context: FragmentActivity, isFromUser: Boolean) {
    //     Timber.i("checkBuglyUpdate isFromUser = $isFromUser")
    //     MainScope().launch(Dispatchers.IO) {
    //         Beta.checkUpgrade(isFromUser, true)
    //         delay(2000).run {
    //             val result = Beta.getUpgradeInfo()
    //             if (result == null) {
    //                 Timber.i("没有新版本")
    //                 if (isFromUser) {
    //                     ToastUtils.show("没有新版本")
    //                 }
    //             } else {
    //                 if (!canShowUpdateDialog(result.versionCode) && !isFromUser) {
    //                     Timber.i("checkBuglyUpdate canShowUpdateDialog return")
    //                     return@launch
    //                 }
    //                 MainScope().launch {
    //                     val appName = Utils.getManifestPlaceholder("APP_NAME")
    //                     val fileSize = "${((result.fileSize * 1.0) / 1024 / 1024).roundUp(2)}M"
    //                     Timber.i("checkBuglyUpdate appName $appName, fileSize = $fileSize, versionCode = ${result.versionCode}, upgradeType = ${result.upgradeType}, newFeature = ${result.newFeature}")
    //                     Timber.i("checkBuglyUpdate apkUrl = ${result.apkUrl}")
    //                     XPopup.Builder(context)
    //                         .isDarkTheme(AppConfig.isDarkTheme())
    //                         .customAnimator(IOSStyleDialogAnimator())
    //                         .asCustom(
    //                             UpdateDialog(
    //                                 context,
    //                                 "${if (appName.isNotEmpty()) "小妖" else appName}${result.versionName}",
    //                                 result.versionCode,
    //                                 fileSize,
    //                                 result.newFeature,
    //                                 result.apkUrl,
    //                                 result.upgradeType == 2,//1:建议 2:强制 3:手工
    //                                 false
    //                             )
    //                         ).show()
    //                 }
    //             }
    //         }
    //     }
    // }
    /**
     * 检查升级
     */
    fun checkUpdate(context: FragmentActivity, isFromUser: Boolean = false) {
        // val abis = Utils.getABIs()
        // if (abis.contains("arm64") || abis.contains("aarch64")) {
        //     Timber.i("checkUpdate isFromUser = $isFromUser, abis = $abis，version = ${Build.VERSION.SDK_INT}")
        //     if (isFromUser) { //64位架构，启动时会自动检测升级，不需要主动调用Beta.checkUpgrade()，如果是用户主动升级，需要调用这个检查
        //         Beta.checkUpgrade()
        //     }
        // } else {
        //通过蒲公英升级，启动时APP中不会检查，则需要每次都调用checkPgyerUpdate检查升级
        checkPgyerUpdate(context, isFromUser)
        //     return
        // }
    }
}